/**
 * 代理模式
 * 1. 使用者无权访问目标对象
 * 2. 中间加代理，通过代理做授权和控制
 * 示例: 科学上网、明星经纪人
 */

class ReadImg {
  constructor(fileName) {
    this.fileName = fileName;
    this.loadFromDisk(); // 初始化即从硬盘中加载，模拟
  }
  display() {
    console.log(`display... ${this.fileName}`);
  }
  loadFromDisk() {
    console.log(`loading... ${this.fileName}`);
  }
}

class ProxyImg {
  constructor(fileName) {
    this.realImg = new ReadImg(fileName);
  }
  display() {
    this.realImg.display();
  }
}

// 测试
let proxyImg = new ProxyImg("1.png");
proxyImg.display();

/**
 * ES6 Proxy
 */

// 明星
let star = {
  name: "Hugo",
  age: 28,
  phone: "star: 13088886666",
};

// 经纪人
let agent = new Proxy(star, {
  get: function (target, key) {
    if (key === "phone") {
      // 返回经纪人自己的手机号
      return "agent: 18622224444";
    }
    if (key === "price") {
      // 明星不报价，经纪人报价
      return 120000;
    }
    return target[key];
  },
  set: function (target, key, val) {
    if (key === "customPrice") {
      if (val < 100000) {
        // 最低 10w
        throw new Error("价格太低");
      } else {
        target[key] = val;
        return true;
      }
    }
  },
});

// test
console.log(agent.name);
console.log(agent.age);
console.log(agent.phone);
console.log(agent.price);

agent.customPrice = 150000;
console.log(`agent.customPrice: ${agent.customPrice}`);
agent.customPrice = 90000;
console.log(`agent.customPrice: ${agent.customPrice}`);
